package javaroke.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

//import Javaroke.dao.BaseDAO;

import javaroke.excepcion.DAOExcepcion;
import javaroke.modelo.Noticia;
import javaroke.util.ConexionBD;

public class NoticiaDAO extends BaseDAO{

	
	public Noticia insertar(Noticia vo) throws DAOExcepcion {
		String query = "insert into noticia (TxMensaje, FeNoticia) values (?,?)";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(1, vo.getTxMensaje());
			stmt.setString(2, vo.getFeNoticia());
			
			
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo insertar");
			}
			
			// Obtener el ultimo id
			
			int id = 0;
			query = "select last_insert_id()";
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			
			if (rs.next()) {
			id = rs.getInt(1)-1;
			 }
			
			vo.setIdNoticia(id);
			

		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}

	
	public Collection<Noticia> listar() throws DAOExcepcion {
		Collection<Noticia> c = new ArrayList<Noticia>();
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = ConexionBD.obtenerConexion();
			String query = "select idNoticia,TxMensaje,FeNoticia from noticia where FeNoticia >= '2013/09/14' ";
			 
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			while (rs.next()) {
				Noticia vo = new Noticia();
				vo.setIdNoticia(rs.getInt("idNoticia"));
				vo.setTxMensaje(rs.getString("TxMensaje"));
				vo.setFeNoticia(rs.getString("FeNoticia"));
				c.add(vo);
			}

		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return c;
	}
	
	
}
